<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getParagrapgPronunciation } from '../api/paragraph';
import axios from 'axios'; // Import axios for making HTTP requests

const route = useRoute();
const router = useRouter();

const article = ref({
  id: '',
  title: '',
  content: []
});

// 加载文章内容
const loadArticleContent = async () => {
  try {
    const id = route.query.id;
    if (!id) {
      ElMessage.error('文章ID缺失');
      router.push('/');
      return;
    }

    const res = await getParagrapgPronunciation(id);
    if (res.data && res.data.list) {
      article.value.id = id;
      article.value.title = `文章 ${id}`;
      article.value.content = res.data.list.map(item => ({
        id: item.id,
        text: item.content.split('').map(char => ({ char, style: {} })), // 字符数组
        fontStyle: item.font === 1 ? 'SimSun' : item.font === 2 ? 'KaiTi' : 'inherit', // 根据font设置字体
        font: item.font // 保存当前段落的font值
      }));
    } else {
      ElMessage.error('未找到文章内容');
      router.push('/');
    }
  } catch (error) {
    console.error('加载文章内容失败：', error);
    ElMessage.error('加载文章内容失败');
  }
};

// 修改段落字体
const updateParagraphFont = async (paragraph, font) => {
  try {
    const res = await axios.get(`http://localhost:8081/paragraph/updateFont?font=${font}&paragraphId=${paragraph.id}`);
    if (res.data.code === 200) {
      ElMessage.success(res.data.data || '修改成功');
      paragraph.font = font; // 更新段落的font值
      paragraph.fontStyle = font === 1 ? 'SimSun' : font === 2 ? 'KaiTi' : 'inherit'; // 更新段落的字体样式
    } else {
      ElMessage.error(res.data.message || '修改失败');
    }
  } catch (error) {
    console.error('修改段落字体失败：', error);
    ElMessage.error('修改段落字体失败');
  }
};

const selectedCharacters = ref([]); // 选中的字符对象数组

// 点击字符，选中并高亮
const handleCharacterClick = (char) => {
  const index = selectedCharacters.value.indexOf(char);
  if (index > -1) {
    // 如果已选中，则取消选中
    selectedCharacters.value.splice(index, 1);
    char.style.backgroundColor = ''; // 清除高亮
  } else {
    // 如果未选中，则添加到选中数组
    selectedCharacters.value.push(char);
    char.style.backgroundColor = '#d3f9d8'; // 设置高亮
  }
};

// 应用样式
const applyStyleToCharacter = (style) => {
  selectedCharacters.value.forEach((char) => {
    char.style = { ...char.style, ...style };
  });
};

onMounted(() => {
  loadArticleContent();
});
</script>

<template>
  <div class="font-design">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>设计字体 - {{ article.title }}</span>
          <el-button type="primary" link @click="router.push('/')">返回列表</el-button>
        </div>
      </template>

      <div class="content-container">
        <div
          v-for="(paragraph, paragraphIndex) in article.content"
          :key="paragraphIndex"
          class="paragraph"
          :style="{ fontFamily: paragraph.fontStyle }"
        >
          <div class="paragraph-header">
            段落 {{ paragraphIndex + 1 }}
            <el-select
              v-model="paragraph.font"
              placeholder="选择字体"
              @change="updateParagraphFont(paragraph, $event)"
              style="margin-left: 10px; width: 120px;"
            >
              <el-option label="宋体" :value="1"></el-option>
              <el-option label="楷体" :value="2"></el-option>
            </el-select>
          </div>

          <div class="character-grid">
            <span
              v-for="(charObj, charIndex) in paragraph.text"
              :key="charIndex"
              class="character"
              :style="charObj.style"
              @click="handleCharacterClick(charObj)"
            >
              {{ charObj.char }}
            </span>
          </div>
        </div>

        <div class="toolbar">
          <el-button type="primary" @click="applyStyleToCharacter({ fontWeight: 'bold' })">加粗</el-button>
          <el-button type="primary" @click="applyStyleToCharacter({ fontStyle: 'italic' })">斜体</el-button>
          <el-button type="primary" @click="applyStyleToCharacter({ textDecoration: 'underline' })">下划线</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.font-design {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-container {
  margin-top: 20px;
}

.paragraph {
  margin-bottom: 20px;
}

.paragraph-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.character-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.character {
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.character:hover {
  background-color: #f5f5f5;
}

.character[style*="background-color: #d3f9d8"] {
  border-color: #67c23a; /* 高亮时边框颜色 */
}

.toolbar {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}
</style>
